package com.the9.C9Alarm;

import java.util.ArrayList;

import org.achartengine.ChartFactory;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import weibo.SinaWeiboOAuthActivity;
import weibo.TXWeiboOAuthActivity;
import weibo.WeiboConstant;

import com.openfeint.api.OpenFeint;
import com.openfeint.api.ui.Dashboard;
import com.openfeint.internal.OpenFeintInternal;
import com.the9.C9Alarm.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ShareToFriendActivity extends Activity implements ClickListener {
	Uri uri;
	String access = null;
	Gallery g;
	private Gallery mGallery;
	int alarm_count;

	boolean weiboBtEnable = true;
	boolean the9BtEnable = true;
	boolean isLaichuang = true;

	private static boolean isLaiChuang;
	private static int awakeTime = 0;
	ImageButton sinawWeiboIBt;
	ImageButton openfeintIBt;
	ImageView titleIm;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("ShareToFriendActivity", "oncreate");
		setContentView(R.layout.awake);
		initUI();
		// awakeTime =
		// getIntent().getBundleExtra(getString(R.string.sleepState)).getInt(getString(R.string.awakeTime));
		awakeTime = Utils.getLaichuangTime();
		Utils.setLaichuangTime(0);

		titleIm = (ImageView) findViewById(R.id.imageView1);
		if (awakeTime > 60) {
			isLaichuang = true;
			titleIm.setBackgroundResource(R.drawable.success);
		} else {
			isLaichuang = false;
			titleIm.setBackgroundResource(R.drawable.fail);
		}

		//
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		Scale.setDm(dm);

		ImageAdapter im = new ImageAdapter(this, this, awakeTime);

		mFlipper = (ViewFlipper) findViewById(R.id.gallery);

		mFlipper.addView(im.getView(1, null, null));
		// mFlipper.addView(im.getView(0, null, null));

		// mFlipper.addView(new AverageTemperatureChart().execute(this));
		_GestureDetector = new GestureDetector(new GestureCallBack(mFlipper));
	}

	ImageView BTsinaWeibo;
	ImageView BTtxWeibo;
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refreshBindState();
	}

	private void initUI() {
		BTsinaWeibo = (ImageView) findViewById(R.id.sinaweibo);
		BTtxWeibo = (ImageView) findViewById(R.id.txweibo);

		BTsinaWeibo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (AlarmApplication.getApp().weiboUser.isSinaBind()) {
					AlarmApplication.getApp().weiboUser
							.removeBindTX(ShareToFriendActivity.this);
					refreshBindState();
					// new
					// MyDialog(WeiboManageActivity.this).show(MyDialog.sina);
				} else {
					Intent i = new Intent();
					i.setClass(ShareToFriendActivity.this,
							SinaWeiboOAuthActivity.class);
					startActivity(i);
					Toast.makeText(ShareToFriendActivity.this, "跳转新浪微博授权页面",
							Toast.LENGTH_SHORT).show();
				}
			}

		});

		BTtxWeibo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (AlarmApplication.getApp().weiboUser.isTxBind()) {
					AlarmApplication.getApp().weiboUser
					.removeBindSina(ShareToFriendActivity.this);
					refreshBindState();
				} else {
					Intent i = new Intent();
					i.setClass(ShareToFriendActivity.this,
							TXWeiboOAuthActivity.class);
					startActivity(i);
					Toast.makeText(ShareToFriendActivity.this, "跳转腾讯微博授权页面",
							Toast.LENGTH_SHORT).show();
				}
			}

		});

	}

	private void refreshBindState() {
		if (AlarmApplication.getApp().weiboUser.isSinaBind()) {
			BTsinaWeibo.setImageResource(R.drawable.logo_sina);
		} else {
			BTsinaWeibo.setImageResource(R.drawable.logo_sina_dead);
		}

		if (AlarmApplication.getApp().weiboUser.isTxBind()) {
			BTtxWeibo.setImageResource(R.drawable.logo_tx);
		} else {
			BTtxWeibo.setImageResource(R.drawable.logo_tx_dead);
		}
	}

	ViewFlipper mFlipper;
	GestureDetector _GestureDetector;
	boolean isWeiboAccessStart = false;
	Object obj_lock = new Object();

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private class ImageAdapter extends BaseAdapter {
		private Context mContext;

		int time;
		int size = 2;
		ClickListener cls;

		public ImageAdapter(Context c, ClickListener cls, int time) {
			mContext = c;
			this.cls = cls;
			this.time = time;
			this.mInflater = LayoutInflater.from(c);

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub

			return size;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub

			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			switch (position) {
			case 0:
				return getTestPicView(position, convertView, parent);
			case 1:
				return getComView(position, convertView, parent);
			default:
				return null;
			}

		}

		Viewsll vs;
		ArrayList<View> vlist;

		private View getTestPicView(int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				vs = new Viewsll(mContext, time);
				vs.addButton(30, 500, 500, 50, BitmapFactory.decodeResource(
						mContext.getResources(), R.drawable.logo_sina),
						ShareToFriendActivity.this);
				vs.doDraw();

				vs.postInvalidate();
				return vs;
			} else {
				convertView.postInvalidate();
				return convertView;
			}

		}

		ViewHolder holder;
		private LayoutInflater mInflater;

		public View getComView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.layout_gallery, null);

				holder.editText = (EditText) convertView
						.findViewById(R.id.editText1);
				holder.iButton = (ImageButton) convertView
						.findViewById(R.id.imageButton1);
				holder.tv = (TextView) convertView.findViewById(R.id.textView1);
				holder.tv_face = (TextView) convertView
						.findViewById(R.id.textView2);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			String[] buff = SleepText.getText(time, isLaiChuang).split(
					Symbol.SPLIT);
			holder.tv.setText(buff[0]);
			holder.tv_face.setText(buff[1]);

			holder.iButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (Utils.checkNetWork(ShareToFriendActivity.this) == true) {

						cls.onUpdateStatusClick(holder.tv.getText().toString()
								+ holder.tv_face.getText().toString() + "  "
								+ holder.editText.getText().toString());
					} else {
						Toast.makeText(ShareToFriendActivity.this, "无网络链接", 1000);
					}
				}

			});
			return convertView;
		}

		public final class ViewHolder {

			public EditText editText;
			public TextView tv;
			public TextView tv_face;
			public ImageButton iButton;
		}

	}

	boolean isWeiboSendStart = false;
	Object send_lock = new Object();

	@Override
	public void onUpdateStatusClick(final String status) {
		// TODO Auto-generated method stub
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				OpenFeintInternal.getInstance().displayErrorDialog("正在发送新浪微博");

				AlarmApplication.getApp().weiboUser.sendSinaWeibo(ShareToFriendActivity.this, status);

				isWeiboSendStart = false;

			}

		});

		if (weiboBtEnable == true) {
			synchronized (obj_lock) {
				if (isWeiboSendStart == false) {
					isWeiboSendStart = true;
					thread.start();
				}

			}

		}

	}

	class GestureCallBack implements OnGestureListener {
		ViewFlipper flipper;

		public GestureCallBack(ViewFlipper vf) {
			super();
			this.flipper = vf;
			// TODO Auto-generated constructor stub
		}

		private int mCurrentLayoutState = 0;
		private static final int FLING_MIN_DISTANCE = 100;
		private static final int FLING_MIN_VELOCITY = 200;

		/**
		 * 此方法在本例中未用到，可以指定跳转到某个页面
		 * 
		 * @param switchTo
		 */
		public void switchLayoutStateTo(int switchTo) {
			while (mCurrentLayoutState != switchTo) {
				if (mCurrentLayoutState > switchTo) {
					mCurrentLayoutState--;
					mFlipper.setInAnimation(inFromLeftAnimation());
					mFlipper.setOutAnimation(outToRightAnimation());
					mFlipper.showPrevious();
				} else {
					mCurrentLayoutState++;
					mFlipper.setInAnimation(inFromRightAnimation());
					mFlipper.setOutAnimation(outToLeftAnimation());
					mFlipper.showNext();
				}

			}
			;
		}

		/**
		 * 定义从右侧进入的动画效果
		 * 
		 * @return
		 */
		protected Animation inFromRightAnimation() {
			Animation inFromRight = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, +1.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f);
			inFromRight.setDuration(500);
			inFromRight.setInterpolator(new AccelerateInterpolator());
			return inFromRight;
		}

		/**
		 * 定义从左侧退出的动画效果
		 * 
		 * @return
		 */
		protected Animation outToLeftAnimation() {
			Animation outtoLeft = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, -1.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f);
			outtoLeft.setDuration(500);
			outtoLeft.setInterpolator(new AccelerateInterpolator());
			return outtoLeft;
		}

		/**
		 * 定义从左侧进入的动画效果
		 * 
		 * @return
		 */
		protected Animation inFromLeftAnimation() {
			Animation inFromLeft = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, -1.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f);
			inFromLeft.setDuration(500);
			inFromLeft.setInterpolator(new AccelerateInterpolator());
			return inFromLeft;
		}

		/**
		 * 定义从右侧退出时的动画效果
		 * 
		 * @return
		 */
		protected Animation outToRightAnimation() {
			Animation outtoRight = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, +1.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_PARENT, 0.0f);
			outtoRight.setDuration(500);
			outtoRight.setInterpolator(new AccelerateInterpolator());
			return outtoRight;
		}

		public boolean onDown(MotionEvent e) {
			// TODO Auto-generated method stub
			return false;
		}

		/*
		 * 用户按下触摸屏、快速移动后松开即触发这个事件 e1：第1个ACTION_DOWN MotionEvent
		 * e2：最后一个ACTION_MOVE MotionEvent velocityX：X轴上的移动速度，像素/秒
		 * velocityY：Y轴上的移动速度，像素/秒 触发条件 ：
		 * X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒
		 */
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
					&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
				// 当像左侧滑动的时候
				// 设置View进入屏幕时候使用的动画
				mFlipper.setInAnimation(inFromRightAnimation());
				// 设置View退出屏幕时候使用的动画
				mFlipper.setOutAnimation(outToLeftAnimation());
				mFlipper.showNext();
			} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
					&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
				// 当像右侧滑动的时候
				mFlipper.setInAnimation(inFromLeftAnimation());
				mFlipper.setOutAnimation(outToRightAnimation());
				mFlipper.showPrevious();
			}
			return false;
		}

		public void onLongPress(MotionEvent e) {
			// TODO Auto-generated method stub

		}

		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			return false;
		}

		public void onShowPress(MotionEvent e) {
			// TODO Auto-generated method stub

		}

		public boolean onSingleTapUp(MotionEvent e) {
			// TODO Auto-generated method stub
			return false;
		}

	}

	// TODO：
	// @Override
	// public boolean onTouchEvent(MotionEvent event) {
	// // TODO Auto-generated method stub
	// //������ �¼�����ʱ���Լ������?�������_GestureDetector������
	// return _GestureDetector.onTouchEvent(event);
	// }

}